/*
 * @Author: likang xie
 * @Date: 2020-12-21 10:14:56
 * @Purpose: 上传文件相关
 */

import globalData from "@/globalData";

/**
 * 上传文件
 * @param url 上传地址
 * @param name 文件名称
 * @param filePath 文件临时地址
 * @param formData 请求参数
 */
export let uploadFile = (options = {}) => {
  console.log("上传参数：", options);
  let { url = "", name = "file", filePath = "", formData = {} } = options;

  // #ifdef H5
  url = `/api${url}`;
  // #endif

  // #ifndef H5
  url = `${globalData.remote}${url}`;
  // #endif

  return new Promise((resolve, reject) => {
    uni.showLoading({
      mask: true,
    });

    uni.uploadFile({
      url,
      name,
      filePath,
      formData,
      header: {
        accessToken: uni.getStorageSync("access_token") || "",
      },
      success: (res) => {
        console.log("上传文件成功：", res);
        uni.hideLoading();

        let info = JSON.parse(res.data);
        if (info.code == 200) {
          resolve(info.data);
        } else {
          reject(info);
        }
      },
      fail: (err) => {
        console.logo("上传文件失败：", err);
        uni.hideLoading();
        reject(err);
      },
    });
  });
};

/**
 * 获取文件的本地临时路径
 * @param file 文件
 */
export let getFileBase64Url = (file = null) => {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader();
    fileReader.readAsDataURL(file);

    fileReader.onload = (event) => {
      let filePath = event.target.result;
      resolve(filePath);
    };

    fileReader.onerror = (err) => {
      reject(err);
    };
  });
};

/**
 * 选择图片
 */
export let chooseImage = (options = {}) => {
  let { count = 9 } = options;
  return new Promise((resolve, reject) => {
    // 选择图片
    uni.chooseImage({
      count,
      sizeType: ["compressed"],
      success: (res) => {
        console.log("选择图片成功：", res);

        // 上传文件队列
        let uploadTask = [];
        res.tempFilePaths.map((filePath) => {
          uploadTask.push(
            uploadFile({
              ...options,
              filePath,
            })
          );
        });

        Promise.all(uploadTask)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      },
      fail: (err) => {
        console.logo("选择图片失败：", err);
        reject(err);
      },
    });
  });
};

/**
 * 选择视频
 */
export let chooseVideo = (options = {}) => {
  return new Promise((resolve, reject) => {
    // 选择图片
    uni.chooseVideo({
      compressed: true,
      success: (res) => {
        console.log("选择视频成功：", res);
        let filePath = res.tempFilePath;

        // 上传文件
        uploadFile({
          ...options,
          filePath,
        })
          .then((res) => {
            resolve([res]);
          })
          .catch((err) => {
            reject(err);
          });
      },
      fail: (err) => {
        console.logo("选择视频失败：", err);
        reject(err);
      },
    });
  });
};

/**
 * 选择附件
 */
export let chooseAttachment = (options = {}) => {
  return new Promise((resolve, reject) => {
    // H5选择
    // #ifdef H5
    let input = document.createElement("input");
    input.type = "file";
    input.accept = "*";
    input.multiple = true;
    input.hidden = true;
    document.documentElement.append(input);
    input.click();

    input.onchange = () => {
      console.log("选择附件成功：", input.files);
      // 生成文件临时地址
      let craeteTask = [];
      Array.from(input.files).map((file) => {
        craeteTask.push(getFileBase64Url(file));
      });

      Promise.all(craeteTask)
        .then((tempFilePaths) => {
          // 上传文件队列
          let uploadTask = [];
          tempFilePaths.map((filePath) => {
            uploadTask.push(
              uploadFile({
                ...options,
                filePath,
              })
            );
          });

          Promise.all(uploadTask)
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        })
        .catch((err) => {
          reject(err);
        });
    };
    // #endif

    // 微信小程序选择
    // #ifdef MP-WEIXIN

    // #endif

    // APP选择
    // #ifdef APP-PLUS

    // #endif
  });
};
